package com.ks.winterwarmimage;

import androidx.annotation.StringRes;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.ks.winterwarmimage.adapter.AccountAdapter;
import com.ks.winterwarmimage.database.DatabaseManager;
import com.ks.winterwarmimage.esptouch.EspTouchManage;
import com.ks.winterwarmimage.utils.BasicsUtil;

import java.util.ArrayList;
import java.util.List;
/**
 * 账户管理界面
 */
public class AccountActivity extends BaseActivity implements View.OnClickListener {
    private TextView textTitle;
    private ListView listAccount;
    private AccountAdapter adapter;
    private List<AccountAdapter.Account> accountList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account);
        textTitle = findViewById(R.id.text_title);
        textTitle.setText(R.string.account_manage);
        listAccount=findViewById(R.id.list_account);
        findViewById(R.id.img_return).setOnClickListener(this);
        findViewById(R.id.btn_create_account).setOnClickListener(this);
        initData();
    }
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            finish();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    public void onClick(View view) {
        switch(view.getId()){
            case R.id.img_return:
                this.setResult(RESULT_CODE+2);
                finish();
                break;
            case R.id.btn_create_account:
                //显示输入对话框来创建账户（8字节）
                showInputDialog(R.string.create_account,R.string.account_input_msg);
                break;
        }
    }
    /**
     * 初始化账户数据列表并绑定
     */
    private void initData(){
        accountList=new ArrayList<>();
        List<String> accountIds= DatabaseManager.getAccountList();
        int currentPosition= DatabaseManager.getCurrentAccountPosition();
        if(accountIds!=null && accountIds.size()>0){
            for(int i=0;i<accountIds.size();i++){
                AccountAdapter.Account account=new AccountAdapter.Account(accountIds.get(i),i==currentPosition);
                account.forward=true;
                accountList.add(account);
            }
        }
        adapter=new AccountAdapter(this,accountList);
        listAccount.setAdapter(adapter);
    }

    /**
     * 显示对话框
     * @param titleResId
     * @param message
     */
    private void showInputDialog(@StringRes int titleResId, @StringRes int message) {
        // 创建一个输入框对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(titleResId);
        builder.setMessage(message);
        final EditText input = new EditText(this);
        TextView textCount=new TextView(this);
        //textCount.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
        textCount.setTextColor(getColor(android.R.color.darker_gray));
        textCount.setGravity(Gravity.RIGHT);
        textCount.setPadding(15, 0, 15, 0);
        input.setBackgroundResource(R.drawable.white_background);
        input.setPadding(15, 15, 15, 15);
        // 将EditText添加到自定义布局中，以便可以控制边距
        LinearLayout customLayout = new LinearLayout(this);
        customLayout.setOrientation(LinearLayout.VERTICAL);
        int padding_y = BasicsUtil.dp2px(this, 5);
        int padding_x = BasicsUtil.dp2px(this, 15);
        customLayout.setPadding(padding_x, padding_y, padding_x, padding_y); // 设置布局的边距
        customLayout.addView(input, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        customLayout.addView(textCount, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        // 设置自定义布局到对话框中
        builder.setView(customLayout);
        builder.setPositiveButton(android.R.string.ok, (dialog, which) -> {
            if(!TextUtils.isEmpty(input.getText()) && input.getText().length()>0){
                // 获取输入内容
                String accountId = input.getText().toString();
                if(accountId.getBytes(EspTouchManage.GB2312).length==8) {
                    DatabaseManager.updateAccount(accountId);               //更新账户信息
                    DatabaseManager.updateCurrentAccountPosition(accountList.size());  //更新当前账户位置
                    AccountAdapter.Account account=new AccountAdapter.Account(accountId,true);
                    account.forward=true;
                    accountList.add(account);
                    adapter.selectItem(accountList.size()-1);
                    adapter.notifyDataSetChanged();
                    dialog.dismiss();                                       //关闭对话框
                }
            }
        });
        builder.setNegativeButton(android.R.string.cancel, (dialog, which) -> {
            dialog.dismiss();    //关闭对话框
        });
        // 创建并显示对话框
        AlertDialog dialog = builder.create();
        // 设置输入框监听器, 用于控制确定按钮的启用/禁用
        input.addTextChangedListener(new TextWatcher(){
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // 文本改变之前的回调，这里不需要实现任何逻辑
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 文本改变时的回调
                if(TextUtils.isEmpty(s)){
                    dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
                    textCount.setText("0/8");
                }else {
                    int bCount= s.toString().getBytes(EspTouchManage.GB2312).length ;
                    boolean enableButton = bCount == 8;
                    dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(enableButton);
                    textCount.setText(String.format("%d/8", bCount));
                    if(bCount<8){
                        textCount.setTextColor(getColor(android.R.color.darker_gray));
                    }else if(bCount==8){
                        textCount.setTextColor(getColor(android.R.color.holo_green_light));
                    }else{
                        textCount.setTextColor(getColor(android.R.color.holo_red_light));
                    }
                }
            }
            @Override
            public void afterTextChanged(Editable editable) {
                // 文本改变之后的回调，这里不需要实现任何逻辑
            }
        });
        dialog.show();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
        textCount.setText("0/8");
    }
}